<template>
  <div class="login-switch-container">
    <!-- 切换容器 -->
    <div class="switch-wrapper"
      ref="switchContainer">
      <!-- 背景滑块 -->
      <div class="slider-track"
        :style="sliderStyle"></div>

      <!-- 切换选项 -->
      <div v-for="(item, index) in switchItems"
        :key="index" class="switch-item"
        :class="{ active: currentIndex === index }"
        @click="handleSwitch(index)">
        {{ item.label }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

const props = defineProps({
  // 默认选中项
  modelValue: {
    type: Number,
    default: 0,
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

const switchItems = [
  { label: '密码登录', value: 'password' },
  { label: '验证码登录', value: 'sms' },
];

// 响应式状态
const currentIndex = ref(props.modelValue);
const containerWidth = ref(0);
const switchContainer = ref < HTMLElement >();

// 计算滑块样式
const sliderStyle = computed(() => ({
  width: `${containerWidth.value / switchItems.length}px`,
  transform: `translateX(${currentIndex.value * 100}%)`,
}));

// 处理切换
const handleSwitch = (index: number) => {
  if (index === currentIndex.value) return;
  currentIndex.value = index;
  emit('update:modelValue', index);
  emit('change', switchItems[index].value);
};

// 初始化容器宽度
onMounted(() => {
  if (switchContainer.value) {
    containerWidth.value = switchContainer.value.offsetWidth;
  }
});
</script>

<style lang="less" scoped>
@primary-color: var(--van-primary-color);
@transition-time: 0.3s;

.login-switch-container {
  padding: 20px 0;
  max-width: 350px;
}

.switch-wrapper {
  position: relative;
  display: flex;
  height: 44px;
  background: #f5f5f5;
  border-radius: 20px;
  overflow: hidden;
  cursor: pointer;
}

.slider-track {
  position: absolute;
  height: 100%;
  background: @primary-color;
  border-radius: 36px;
  transition: all @transition-time cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.switch-item {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #666;
  z-index: 1;
  transition:
    color @transition-time,
    transform @transition-time;

  &.active {
    color: #fff;
    font-weight: 500;
  }

  &:active {
    transform: scale(0.98);
  }
}

// 暗黑模式适配
.van-theme-dark {
  .switch-wrapper {
    background: #2a2a2a;
  }

  .switch-item {
    color: #888;

    &.active {
      color: #fff;
    }
  }
}
</style>
